package sh.orm;

import lombok.Data;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import sh.orm.convert.JdbcType;
import sh.orm.util.ConnectionPool;
import sh.orm.util.ResultSetUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据库的元数据信息，需要获取连接，并初始化
 * @author lqq
 * @date 2019/2/27
 */
@Slf4j
public class DatabaseMetadata {
    // 数据库操作
    private static final String SQL = "SELECT * FROM ";

    /**
     * 与数据库的连接
     */
    private static Connection conn = ConnectionPool.getInstance().getConnection();


    /**
     * 数据库表名，和表元数据信息
     * key 数据库表名，value：元数据
     *
     */
    @Getter
    private Map<String , TableMetadata> tableMetadataMap = new HashMap<>();

    private static DatabaseMetadata instance;


    private DatabaseMetadata(){
        //获取元数据并初始化
        init();
    }

    public static DatabaseMetadata getInstance(){
        if(instance != null){
            return instance;
        }else{
            synchronized (DatabaseMetadata.class){
                if(instance == null){
                    instance = new DatabaseMetadata();
                }
            }
        }
        return instance;
    }


    private void init(){
        List<String> tables = getTableNames();
        for(String tableName : tables){
            TableMetadata tableMetadata = new TableMetadata();
            tableMetadata.setFieldJdbcTypeMap(getColumnTypes(tableName));
            tableMetadataMap.put(tableName, tableMetadata);
        }

        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static List<String> getTableNames() {
        List<String> tableNames = new ArrayList<>();
        ResultSet rs = null;
        try {
            //获取数据库的元数据
            DatabaseMetaData db = conn.getMetaData();
            //从元数据中获取到所有的表名
            rs = db.getTables(null, null, null, new String[] { "TABLE" });
            while(rs.next()) {
                tableNames.add(rs.getString(3));
            }
        } catch (SQLException e) {
        }
        return tableNames;
    }

    /**
     * 数据库表元数据信息
     */
    @Data
    class TableMetadata{
        /** entity的字段和数据库类型的map，需要加载数据库元数据才能初始化 */

        private Map<String , JdbcType> fieldJdbcTypeMap = new HashMap<>();
    }



    public static Map<String , JdbcType> getColumnTypes(String tableName) {
        PreparedStatement pStemt = null;
        String tableSql = SQL + tableName;
        try {
            pStemt = conn.prepareStatement(tableSql);
            //结果集元数据
            ResultSetMetaData rsmd = pStemt.getMetaData();
            return ResultSetUtil.getColumnNameJdbcTypeMap(rsmd);

        } catch (SQLException e) {

            throw new OrmException("获取数据库元信息异常");
        }
    }


}
